#include "RpcServer.h"
#include <memory>
#include "RpcChannel.h"

using namespace std::placeholders;

RpcServer::RpcServer(EventLoop* loop, int port)
    : server_(loop, port)
{
    server_.setConnectionCallback(std::bind(&RpcServer::onConnection, this, _1));
}

void RpcServer::registerService(google::protobuf::Service* service)
{
    const google::protobuf::ServiceDescriptor* desc = service->GetDescriptor();
    services_[desc->name()] = service;
}

void RpcServer::start()
{
    server_.start();
}

void RpcServer::onConnection(const TcpConnectionPtr& conn)
{
    // std::cout << "RpcServer::onConnection" << std::endl;
    if (conn->connected())
    {
        RpcChannelPtr channel(new RpcChannel(conn));
        channel->setServices(&services_);
        conn->setMessageCallback(
            std::bind(&RpcChannel::onMessage, channel.get(), _1, _2));
        conn->setContext(channel);
    }
    else
    {
        conn->setContext(RpcChannelPtr());
    }
    
}
